package com.yanqu.road.server.manager.activity.bulletscreen;

import com.alibaba.fastjson.JSONArray;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.pb.activity.BulletScreenProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.date.DateHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossActivityBulletScreenMgr extends TempMgr {

    static Map<Integer, CrossActivityBulletScreen> bulletScreenMap = new ConcurrentHashMap<>();

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean stop() {
        return false;
    }
    
    @Override
    public boolean save() {
        return true;
    }

    /**
     * 初始或者加载弹幕数据
     * @param activityId
     */
    public static void initOrReloadMsgData(int activityId, boolean reload) {
        if(!bulletScreenMap.containsKey(activityId) || reload){
            synchronized (bulletScreenMap) {
                if(bulletScreenMap.containsKey(activityId) && !reload){
                    return;
                }
                ActivityInfo inShowTimeActivityInfo = ActivityMgr.getActivityInfoMayLoadDB(activityId);
                if(inShowTimeActivityInfo == null){
                    return ;
                }
                CrossActivityBulletScreen activityBulletScreen = bulletScreenMap.get(activityId);
                if (activityBulletScreen == null) {
                    activityBulletScreen = new CrossActivityBulletScreen(inShowTimeActivityInfo);
                    activityBulletScreen.init();
                    bulletScreenMap.put(inShowTimeActivityInfo.getActivityId(), activityBulletScreen);
                    getLogger().info("init activity {} barrage message", activityId);
                } else {
                    activityBulletScreen.setActivityInfo(inShowTimeActivityInfo);
                    getLogger().info("reset activity {} barrage message", activityId);
                }
            }
        }
    }


    /**
     * 弹幕
     * @param activityId
     * @param content
     * @param userId
     * @return
     */
    public static CrossActivityBarrageMessage addBarrageMessage(int activityId, String content, long userId, String nickName, long serverId) {
        initOrReloadMsgData(activityId, false);
        CrossActivityBulletScreen bulletScreen = bulletScreenMap.get(activityId);
        if(bulletScreen != null){
           return bulletScreen.addBarrageMessage(content, userId, nickName, serverId);
        }
        return null;
    }


    /**
     * 获取弹幕
     * @param activityId
     * @return
     */
    public static void getMessageList(int activityId, long readContentId, long serverId, long playerId, long lastReadTime){
        CrossActivityBulletScreen bulletScreen = bulletScreenMap.get(activityId);
        if(bulletScreen != null){
            List<CrossActivityBarrageMessage> list = bulletScreen.getMessageList();

            //跨服重启，存在已读大于消息大小
            if(readContentId > list.size()){
                readContentId = 0;
                getLogger().info("rest barrage message readContentId for {}:{}", activityId, playerId);
            }
            if(list.size() > 0 && lastReadTime > 0 && lastReadTime < list.get(0).getPostTime()){
                readContentId = 0;
                getLogger().info("rest barrage message readContentId for {}:{}", activityId, playerId);
            }

            List<CrossActivityBarrageMessage> syncList = new ArrayList<>();
            long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp();

            for(CrossActivityBarrageMessage msg : list){
                //消息id大于历史已读且是当天
                if(msg.getContentId() > readContentId && msg.getPostTime() >= zeroTime){
                    syncList.add(msg);
                }
            }

            BulletScreenProto.CrossBulletScreenContentListRespMsg.Builder respMsg = CrossActivityBulletScreenMgr.getMsgListBuilder(syncList);
            respMsg.setActivityId(activityId);
            respMsg.setTotalMsgSize(list.size());
            if(respMsg.getTotalMsgSize() > 0){
                CrossActivityBarrageMessage firstMsg = list.get(0);
                respMsg.setFirstMsgTime(firstMsg.getPostTime());
            }
            respMsg.setRet(0);
            getLogger().info("user {}:{} get Barrage message {}:{}", serverId, playerId, activityId, syncList.size());
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.S_ACTIVITY_LIST_BULLET_SCREEN_COMMENTS_FROM_CROSS, respMsg));
        }
    }

    /**
     * 清理过期数据
     */
    public static void removeOutTimeMsg() {
        //移除过期活动的数据
        long nowTime = DateHelper.getCurrentSecond();
        for (Map.Entry<Integer, CrossActivityBulletScreen> bulletScreenEntry : bulletScreenMap.entrySet()) {
            CrossActivityBulletScreen bulletScreen = bulletScreenEntry.getValue();
            bulletScreen.removeOutTimeMsg();
            if(nowTime > bulletScreen.getActivityInfo().getEndShowTime()){
                bulletScreenMap.remove(bulletScreen.getActivityInfo().getActivityId());
            }
        }
    }

    /**
     * 同步弹幕给区服
     */
    public static void syncBarrageMessageToServer(){
        for (Map.Entry<Integer, CrossActivityBulletScreen> bulletScreenEntry : bulletScreenMap.entrySet()) {
            CrossActivityBulletScreen bulletScreen = bulletScreenEntry.getValue();
            bulletScreen.syncBarrageMessageToServer();
        }
    }

    public static BulletScreenProto.ActivityBarrageMessageTemp.Builder parseBarrageMessageBuilder(CrossActivityBarrageMessage msg, String content, int activityId, long serverId) {
        BulletScreenProto.ActivityBarrageMessageTemp.Builder temp = BulletScreenProto.ActivityBarrageMessageTemp.newBuilder();
        temp.setActivityId(activityId);
        temp.setContent(content);
        temp.setContentId(msg.getContentId());
        temp.setPostTime(msg.getPostTime());
        temp.setUserId(msg.getUserId());
        temp.setServerId(serverId);
        temp.setNickName(msg.getNickName());
        return temp;
    }

    public static BulletScreenProto.CrossBulletScreenContentListRespMsg.Builder getMsgListBuilder(List<CrossActivityBarrageMessage> syncList) {
        BulletScreenProto.CrossBulletScreenContentListRespMsg.Builder respMsg = BulletScreenProto.CrossBulletScreenContentListRespMsg.newBuilder();
        respMsg.setRet(0);
        for(CrossActivityBarrageMessage msg : syncList){
            BulletScreenProto.ActivityBarrageMessageTemp.Builder temp = parseBarrageMessageBuilder(msg, msg.getContent(), msg.getActivityId(), msg.getServerId());
            respMsg.addMsg(temp);
        }
        return respMsg;
    }


    public static BulletScreenProto.BulletScreenContentListRespMsg.Builder getMsgListBuilder2(List<CrossActivityBarrageMessage> syncList) {
        BulletScreenProto.BulletScreenContentListRespMsg.Builder respMsg = BulletScreenProto.BulletScreenContentListRespMsg.newBuilder();
        respMsg.setRet(0);
        for(CrossActivityBarrageMessage msg : syncList){
            BulletScreenProto.ActivityBarrageMessageTemp.Builder temp = parseBarrageMessageBuilder(msg, msg.getContent(), msg.getActivityId(), msg.getServerId());
            respMsg.addMsg(temp);
        }
        return respMsg;
    }

    /**
    * 描述：变更玩家弹幕
    * 作者：zrq
    * 时间：2022/8/5
    * 参数：
    活动编号，玩家编号，服务器编号，变更内容
    * 返回值：操作码
    **/
    public static int changePlayerBulletScreen(int activityId, long userId, long serverId, String content, long contentId) {
        CrossActivityBulletScreen bulletScreen = bulletScreenMap.get(activityId);
        if (null == bulletScreen) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        return bulletScreen.changePlayerMsg(userId, serverId, content, contentId);
    }

    /**
    * 描述：查玩家弹幕内容
    * 作者：zrq
    * 时间：2022/8/23
    * 参数：

    * 返回值：
    **/
    public static JSONArray queryPlayerBulletScreen(int activityId, long userId, long serverId) {
        CrossActivityBulletScreen bulletScreen = bulletScreenMap.get(activityId);
        if (null == bulletScreen) {
            return new JSONArray();
        }
        return bulletScreen.queryPlayerMsg(userId, serverId);
    }
}
